package com.example.demo.security.handler;

import com.alibaba.fastjson.JSON;
import com.example.demo.common.Result;
import com.example.demo.entity.Business;
import com.example.demo.entity.LoginUser;
import com.example.demo.mapper.EmployeeMapper;
import com.example.demo.security.util.JwtUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;



public class AuthSuccessHandler implements AuthenticationSuccessHandler {


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        // 设定响应状态码为200
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        // 设定响应内容是utf-8编码的json类型
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setCharacterEncoding("utf-8");
        // 组装自己的结果对象
        Result result = new Result();
        result.setCode("200");
        result.setMsg("登录成功");
        LoginUser loginUser=(LoginUser) authentication.getPrincipal();
        System.out.println(loginUser);
//        loginUser.setRole(employeeMapper.selectRoleById(loginUser.getId()));
        Map<String,String> payload=new HashMap<>();
        payload.put("id",loginUser.getId().toString());
        payload.put("name",loginUser.getUsername());
        String token= JwtUtils.createToken(payload);
        result.setToken(token);
        result.setData(loginUser);
        // 序列化结果对象为JSON
        String resultJSON = JSON.toJSONString(result);
        // 写入响应体
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(resultJSON);
        writer.flush();
        writer.close();
    }

}
